package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutzyt.delivery.bean.User;
import com.lutzyt.delivery.mapper.UserDAO;
import com.lutzyt.delivery.service.UserRoleService;
import com.lutzyt.delivery.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zyt
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ActionServiceImpl<UserDAO, User> implements UserService {
  public static final String USER_ID = "user_id";

  private UserDAO userDAO;
  private UserRoleService userRoleService;

  @Transactional(readOnly = true)
  @Override
  public User findById(Integer id) {
    return userDAO.selectById(id);
  }

  @Transactional(readOnly = true)
  @Override
  public IPage<User> findByPage(int pageNum, int pageSize) {
    return userDAO.selectPage(new Page<>(pageNum, pageSize), null);
  }

  @Override
  public void insert(User user) {
    userDAO.insert(user);
  }

  @Override
  public void update(User user) {
    userDAO.updateById(user);
  }

  @Override
  public void deleteById(Integer id) {
    userDAO.deleteById(id);
    userRoleService.update().eq(USER_ID, id).remove();
  }

  @Override
  public void deleteByIds(List<String> ids) {
    if (ids.size() == 0) {
      throw new RuntimeException("至少删除一个");
    }
    userDAO.deleteBatchIds(ids);
    userRoleService.update().in(USER_ID, ids).remove();
  }

  @Autowired
  public void setUserRoleService(UserRoleService userRoleService) {
    this.userRoleService = userRoleService;
  }

  @Autowired
  public void setUserDAO(UserDAO userDAO) {
    this.userDAO = userDAO;
  }

  @Override
  public User findByName(String username) {
    return this.query().eq("username", username).one();
  }
}